<?php

if (!defined('TS_ROOT')) die(basename(__FILE__));

class comment_common
{
	function action_submit($blogs_id, $comment)
	{
		global $userdata, $ts_cfg, $lang;
		
		$current_time = TIMENOW;
		
		// флуд контроль
		$row = null;
		$where_sql = (IS_GUEST) ? "bc.comment_user_ip = '". USER_IP ."'" : "bc.comment_user_id = {$userdata['user_id']}";
		
		$sql = "SELECT MAX(bc.comment_time) AS last_post_time FROM ". TS_BLOG_COMMENTS ." bc WHERE $where_sql";
		if ($row = DB()->fetch_row($sql) AND $row['last_post_time'])
		{
			if ($userdata['user_level'] == USER)
			{
				if (TIMENOW - $row['last_post_time'] < $ts_cfg['flood_interval'])
				{
					ts_die($lang['FLOOD_ERROR']);
				}
			}
		}
		
		// Дублирование коментов
		$sql = "
				SELECT bc.comment_text
				FROM ". TS_BLOG_COMMENTS ." bc, ". TS_BLOGS ." b
				WHERE
						$where_sql
					AND bc.comment_time = ". (int) $row['last_post_time'] ."
					AND b.blog_id = bc.blog_id
				LIMIT 1
		";
		
		if ($row = DB()->fetch_row($sql))
		{
			$last_msg = DB()->escape($row['comment_text']);
			
			if ($last_msg == $comment)
			{
				ts_die($lang['DOUBLE_COMMENT_ERROR']);
			}
		}
		
		DB()->query("INSERT INTO 
								". TS_BLOG_COMMENTS ." 
									(blog_id, comment_time, comment_text, comment_user_id, comment_user_ip) 	
								VALUE
									($blogs_id, $current_time, '$comment', ". $userdata['user_id'] .", '". USER_IP ."')");
		
		meta_refresh(BLOG_URL . "$blogs_id");
		set_die_append_msg($blogs_id);
	}
	
	function update_stats($user_id)
	{
		$sql = "UPDATE " . TS_USERS . " SET user_posts = user_posts + 1 WHERE user_id = $user_id";
		if (!DB()->sql_query($sql))
		{
			ts_die('Error in posting #6');
		}
	}

	function delete_comment($blogs_id, $user_id)
	{
		DB()->query("DELETE FROM ". TS_BLOG_COMMENTS ." WHERE comment_id = {$blogs_id}");
		DB()->query("UPDATE ". TS_USERS ." SET user_posts = user_posts - 1 WHERE user_id = $user_id");
	}
}